package com.lx.screenshot.floatWindow;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Build;
import android.provider.Settings;
import android.view.*;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.lx.screenshot.databinding.FloatWindowBinding;
import com.lx.screenshot.ui.ScreenRecordActivity;
import com.lx.screenshot.ui.translation.TranslationFragment;
import com.lx.screenshot.util.DrawableUtil;
import com.lx.screenshot.util.SPUtil;
import com.lx.screenshot.util.ScreenShotUtil;
import com.lx.screenshot.util.SettingUtil;



public class FloatWindow{
    protected final Context context;
    protected final WindowManager.LayoutParams params;
    protected final WindowManager manage;
    protected FrameLayout floatWindow;
    private FloatWindowBinding binding;
    protected float lastX;
    protected float lastY;
    protected boolean isDrag;
    private boolean running = false;
    private boolean created = false;
    private ResultWindow resultWindow;
    private ChooseAreaWindow chooseAreaWin;

    public FloatWindow(Context context) {
        this.context = context;
        manage = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        params = new WindowManager.LayoutParams();
    }

    private void init() {
        if ("com.lx.screenshot.floatWindow.FloatWindow".equals(getClass().getName())) {
            SPUtil.put(context, SettingUtil.HAD_CHOOSE_AREA, false);
        }
    }

    public boolean isRunning() {
        return running;
    }

    public boolean isCreated() {
        return created;
    }

    /**
     * 创建一个悬浮窗，从float_window.xml创建
     */
    public void create() {
        init();
        createWithNoReChooseArea();
    }

    /**
     * 创建一个悬浮窗，从float_window.xml创建
     */
    public void createWithNoReChooseArea() {
        // 初始化布局参数
        initParams();
        // 初始化界面
        initView();
        // 添加触摸事件
        addTouchListener();
        // 添加组件的监听事件
        addClickListener();
        // 添加到manage中
        addToWindowManage();
        // 显示
        show();
        created = true;
    }

    /**
     * 创建一个悬浮窗，从float_window.xml创建
     */
    public void createWithPermissionCheck(Context context) {
        if (!checkFloatPermission()) {
            Toast.makeText(context, "需要设置悬浮窗权限，才能显示悬浮窗", Toast.LENGTH_SHORT).show();
            goToPermissionSetting(context);
        } else {
            create();
//            if (ScreenUtil.isHasPermission()) {
//                create();
//            } else {
//                // 请求截屏权限
////                startCapturePermission();
//            }
        }
    }

    public void createWithPermissionCheck(TranslationFragment context) {
        if (!checkFloatPermission()) {
            Toast.makeText(context.getContext(), "需要设置悬浮窗权限，才能显示悬浮窗", Toast.LENGTH_SHORT).show();
            goToPermissionSetting(context.getContext());
        } else {
            if (ScreenShotUtil.isHasPermission()) {
                create();
//            } else {
//                // 请求截屏权限
//                ScreenUtil.requestPermission(context.getActivity());
            }
        }
    }

    protected void startCapturePermission() {
        // 请求截屏权限
        Intent intent = new Intent(context, ScreenRecordActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    protected void addClickListener() {
        floatWindow.setOnClickListener(v -> {
            if (!ScreenShotUtil.isHasPermission()) {
                startCapturePermission();
            } else {
               startCapture();
            }
        });
    }

    public void startCapture(){
        /*
         * 1、点击一次后弹出选择翻译区域的悬浮窗
         * 2、选择完区域后，保存选择区域的截屏
         * 3、上传图片到api
         * 4、将结果传到结果悬浮窗
         * */

//        Bitmap bitmap = ScreenUtil.screen();
        if(!ScreenShotUtil.isScreenArea){
            ScreenShotUtil.syncScreen();
            return;
        }

        boolean hadChooseArea = SPUtil.get(context, SettingUtil.HAD_CHOOSE_AREA, false);
        boolean simpleUse = SettingUtil.getSetting(context, "floatWin_simpleUse", false);

        if (simpleUse) {
            if (!hadChooseArea) {
                startChooseAreaWin();
            } else {
                if (chooseAreaWin != null) {
                    chooseAreaWin.destroyResultWin();
                    chooseAreaWin = null;
                }
                startResultWin(
                        Float.parseFloat(SettingUtil.getSetting(context, "startX", "0")),
                        Float.parseFloat(SettingUtil.getSetting(context, "startY", "0")),
                        Float.parseFloat(SettingUtil.getSetting(context, "endX", "0")),
                        Float.parseFloat(SettingUtil.getSetting(context, "endY", "0"))
                );
            }
        } else {
            stopResultWin();
            startChooseAreaWin();
        }
    }
    private void startChooseAreaWin() {
        if (chooseAreaWin == null)
            chooseAreaWin = new ChooseAreaWindow(context);
        chooseAreaWin.create();
    }

    protected void startResultWin(float startX, float startY, float endX, float endY) {
        if (resultWindow != null) {
            resultWindow.destroy();
            resultWindow = null;
        }
        // 判断范围是否过小
        if (Math.abs(endX - startX) * Math.abs(endY - startY) > 25 * 50) {
            // 得到截屏范围，输入到结果悬浮窗
            Bitmap bitmap = ScreenShotUtil.screen(startX, startY, endX, endY);
            onScreenResult.screenSuccess(bitmap);
            // 启动结果悬浮窗
//            resultWindow = new ResultWindow(context, startX, startY, endX, endY);
//            resultWindow.create();
        }
    }

    protected void stopResultWin(){
        if (resultWindow!=null){
            resultWindow.destroy();
            resultWindow = null;
        }
    }

    private void addToWindowManage() {
        floatWindow.setVisibility(View.INVISIBLE);
        manage.addView(floatWindow, params);
    }

    @SuppressLint("ClickableViewAccessibility")
    protected void addTouchListener() {
        floatWindow.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    lastX = event.getRawX();
                    lastY = event.getRawY();
                    isDrag = false;
                    break;
                case MotionEvent.ACTION_MOVE:
                    float dx = event.getRawX() - lastX;
                    float dy = event.getRawY() - lastY;

                    isDrag = true;
                    float x = params.x + dx;
                    float y = params.y + dy;

                    params.x = Math.round(x);
                    params.y = Math.round(y);

                    manage.updateViewLayout(floatWindow, params);

                    lastX = event.getRawX();
                    lastY = event.getRawY();

                    break;
                case MotionEvent.ACTION_UP:
                    break;
            }

            return isDrag;
        });
    }

    protected void initView() {
        floatWindow = new FrameLayout(context);
        binding = FloatWindowBinding.inflate(LayoutInflater.from(context), floatWindow, false);
        binding.floatWinIconIV.setImageResource(
                DrawableUtil.parseResPathToInt(context, SettingUtil.getSetting(context, "floatWinIcon", "res/drawable-v24/da_sha_gou_gou_icon.png"))
        );
        floatWindow.addView(
                binding.getRoot()
        );
    }

    protected void initParams() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        params.format = PixelFormat.RGBA_8888;
        params.gravity = Gravity.START;

        // 设置浮窗以外的触摸事件可以传递给后面的窗口、不自动获取焦点
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
    }

    /**
     * 显示悬浮窗
     */
    public void show() {
        if (floatWindow != null) {
            floatWindow.setVisibility(View.VISIBLE);
            running = true;
        }
    }

    /**
     * 隐藏悬浮窗
     */
    public void hide() {
        if (floatWindow != null) {
            floatWindow.setVisibility(View.INVISIBLE);
            running = false;
        }
    }

    /**
     * 销毁悬浮窗
     */
    public void destroy() {
        if (floatWindow != null) {
            manage.removeViewImmediate(floatWindow);
            floatWindow = null;
            running = false;
            created = false;
        }
    }

    /**
     * 检查是否有悬浮窗权限
     *
     * @return true代表有悬浮窗权限
     */
    private boolean checkFloatPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return Settings.canDrawOverlays(context);
        }
        return true;
    }


    /**
     * 跳转到本应用的悬浮窗设置
     */
    private void goToPermissionSetting(Context context1) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 请求截屏权限
            Intent intent = new Intent(context, ScreenRecordActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("from", "float");
            context.startActivity(intent);

        }
    }



    public void destroyResultWin() {
        stopResultWin();
    }

    private static OnScreenResult onScreenResult;
    public static void setOnScreenResult(OnScreenResult onScreenResult){
        FloatWindow.onScreenResult = onScreenResult;
    }

}
